<?php
namespace FastPHP\Core;

class Router
{
    public $group = 'home';
    public $controller = 'Index';
    public $action = 'index';
    public $params = [];
    protected $routes = [];
    protected $suffix = 'html';
    protected $mode = 'auto';

    public function __construct()
    {
        // 读取全局路由配置
        $routeConfig = config('app.route', []);
        if (!empty($routeConfig['suffix'])) {
            $this->suffix = $routeConfig['suffix'];
        }
        if (!empty($routeConfig['mode'])) {
            $this->mode = $routeConfig['mode'];
        }
        // 优先APP_GROUP
        if (defined('APP_GROUP')) {
            $this->group = APP_GROUP;
        }
        // 加载路由配置
        $this->loadRoutes();
        // 路由模式判断
        $pathInfo = $this->getPathInfo();
        if ($this->mode === 'query') {
            // 只支持传统参数
            if (isset($_GET['s'])) $this->group = $_GET['s'];
            if (isset($_GET['c'])) $this->controller = $_GET['c'];
            if (isset($_GET['a'])) $this->action = $_GET['a'];
            $this->params = $_GET;
        } else {
            // auto/pathinfo
            if ($pathInfo && $this->matchRoute($pathInfo)) {
                return;
            } elseif ($pathInfo) {
                $this->parsePathInfo($pathInfo);
            } else {
                if (isset($_GET['s'])) $this->group = $_GET['s'];
                if (isset($_GET['c'])) $this->controller = $_GET['c'];
                if (isset($_GET['a'])) $this->action = $_GET['a'];
                $this->params = $_GET;
            }
        }
    }

    protected function loadRoutes()
    {
        $routerFile = APP_PATH . $this->group . '/app/config/router.php';
        if (file_exists($routerFile)) {
            $routes = require $routerFile;
            if (is_array($routes)) {
                $this->routes = $routes;
            }
        }
    }

    protected function matchRoute($pathInfo)
    {
        $pathInfo = trim($pathInfo, '/');
        $pathInfo = $this->removeSuffix($pathInfo);
        foreach ($this->routes as $rule => $route) {
            // 正则路由
            if (is_int($rule) && is_array($route)) {
                foreach ($route as $reg => $target) {
                    if (preg_match('#^' . $reg . '$#i', $pathInfo, $matches)) {
                        $this->setRouteTarget($target);
                        if (count($matches) > 1) {
                            $this->params = array_merge($this->params, array_slice($matches, 1));
                        }
                        return true;
                    }
                }
                continue;
            }
            // 动态参数 :param
            if (strpos($rule, ':') !== false) {
                $reg = preg_replace('/\:([a-zA-Z0-9_]+)/', '([^/]+)', $rule);
                if (preg_match('#^' . $reg . '$#i', $pathInfo, $matches)) {
                    $this->setRouteTarget($route);
                    preg_match_all('/\:([a-zA-Z0-9_]+)/', $rule, $paramNames);
                    if (!empty($paramNames[1])) {
                        foreach ($paramNames[1] as $idx => $name) {
                            $this->params[$name] = $matches[$idx + 1];
                        }
                    }
                    return true;
                }
            } else {
                // 静态路由
                if (trim($rule, '/') === $pathInfo) {
                    $this->setRouteTarget($route);
                    return true;
                }
            }
        }
        return false;
    }

    protected function setRouteTarget($route)
    {
        if (is_array($route)) {
            $routeStr = $route[0];
        } else {
            $routeStr = $route;
        }
        $parts = explode('/', $routeStr);
        if (count($parts) === 2) {
            $this->controller = $parts[0];
            $this->action = $parts[1];
        } elseif (count($parts) === 1) {
            $this->controller = $parts[0];
            $this->action = 'index';
        }
    }

    protected function getPathInfo()
    {
        if (!empty($_SERVER['PATH_INFO'])) {
            return $_SERVER['PATH_INFO'];
        }
        if (!empty($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] != '/index.php') {
            return $_SERVER['ORIG_PATH_INFO'];
        }
        $requestUri = $_SERVER['REQUEST_URI'] ?? '';
        $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
        if ($requestUri && strpos($requestUri, $scriptName) === 0) {
            $path = substr($requestUri, strlen($scriptName));
            $q = strpos($path, '?');
            if ($q !== false) $path = substr($path, 0, $q);
            return $path;
        }
        return '';
    }

    protected function parsePathInfo($pathInfo)
    {
        $pathInfo = trim($pathInfo, '/');
        $pathInfo = $this->removeSuffix($pathInfo);
        $segments = explode('/', $pathInfo);
        $i = 0;
        if (!defined('APP_GROUP') && isset($segments[$i])) {
            $this->group = $segments[$i++];
        }
        if (isset($segments[$i])) {
            $this->controller = $segments[$i++];
        }
        if (isset($segments[$i])) {
            $this->action = $segments[$i++];
        }
        while (isset($segments[$i])) {
            $key = $segments[$i++];
            $val = isset($segments[$i]) ? $segments[$i++] : null;
            $this->params[$key] = $val;
        }
        $this->params = array_merge($_GET, $this->params);
    }

    protected function removeSuffix($pathInfo)
    {
        if ($this->suffix) {
            $pattern = '/\.' . preg_quote($this->suffix, '/') . '$/i';
            $pathInfo = preg_replace($pattern, '', $pathInfo);
        }
        return $pathInfo;
    }
} 